<!--
 * @Author: jiu yin
 * @Date: 2024-04-11 10:50:32
 * @LastEditTime: 2024-04-29 17:35:54
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \web-smart-tour\src\pagesA\ar_navigation\components\nav_button.vue
 * jiu
-->
<template>
	<view class="h-96rpx w-702rpx bg-#fff border-rd-48rpx flex items-center fixed bottom-68rpx left-24rpx p-16rpx box-border z-25">
		<view class="mr-20rpx">
			<!-- <zero-switch
				v-model="switch_value"
				inactive-color="#94ACA6"
				active-color="#0CCA92"
				backgroundColorOff="#E8EDEC"
				backgroundColorOn="#D7F0E8"
				textOff="AI"
				textOn="AI"
				showText
				:size="24"
				@change="switch_change"
			></zero-switch> -->
			<view class="itemBox" @click="goTo">
				<view class="itemBoxLeft">
					<image src="@/static/images/map/rec_line.png" mode="widthFix"></image>
				</view>
				<view class="itemBoxRight">
					<text>推荐路线</text>
				</view>
			</view>	
		</view>

		<button :class="{ but1: true, flex1: true, but2: true, opacity_90: !switch_value_computed }" @longtap.stop="but_speak" @touchend="touchend_speak">
			<image src="../../../static/images/icon_mic.png" class="w-42rpx h-42rpx align-middle mr-24rpx" v-if="!is_but_speak"></image>
			<image src="../../../static/images/icon_wave.png" class="w-42rpx h-42rpx align-middle mr-24rpx" v-else></image>
			{{ is_but_speak ? '松开发送' : '按住说话' }}
		</button>
		<!-- <button class="but1 w-210rpx" @click.stop="but2_map()">{{ map_nav_type_computed == 'ar_nav' ? '地图全览' : '地图还原' }}</button> -->
		<view class="itemBox" @click="but2_map()">
			<view class="itemBoxLeft">
				<image :src="map_nav_type_computed == 'ar_nav' ? '/static/images/punch.png' : '/static/images/map/ar.png'" mode="widthFix"></image>
			</view>
			<view class="itemBoxRight">
				<text>{{ map_nav_type_computed == 'ar_nav' ? '地图导览' : 'AR导航' }}</text>
			</view>
		</view>	
	</view>
</template>

<script>
	import { uploadFile, getSetting } from '@/utils';
	import { baseURLAi } from '@/utils/request';
	import { service } from '@/api/home';
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;

	export default {
		props: ['spotAuth'],
		data() {
			return {
				is_but_speak: false,
				is_permit_speak: true, //长按开关
				voicePath: '',
				scenic_detail: JSON.parse(uni.getStorageSync('scenic_detail')) || {},
				switch_value: true,
				ai_time: null,
			};
		},
		created(options) {},

		computed: {
			map_nav_type_computed() {
				return this.$store.getters.map_nav_type;
			},
			switch_value_computed() {
				return this.$store.getters.switch_value;
			},
		},
		watch: {
			map_nav_type_computed(newVal, oldVal) {
				if (newVal == 'map_nav') {
					this.switch_value = false;
				} else {
					this.switch_value = true;
				}
				this.$store.commit('map/set_switch_value', this.switch_value);
			},
		},
		mounted() {
			this.switch_value = this.switch_value_computed;
			this.onStop();
			this.onError_fn();
		},
		methods: {
			//开关
			switch_change(value) {
				console.log('AI开关', value);
				this.switch_value = value;
				this.$store.commit('map/set_switch_value', value);
			},

			//按钮说话
			async but_speak() {
				if (!this.switch_value_computed) {
					return uni.$u.toast('请打开AI开关');
				}
				//没权限
				if (!this.spotAuth.purchase_status && (!this.spotAuth.experience || this.spotAuth.experience_end_time_stamp == 0)) {
					return this.$emit('no_spotAuth');
				}

				if (!this.is_permit_speak) {
					return uni.$u.toast('上条消息生成中，请稍后再试');
				}
				this.is_permit_speak = false;
				setTimeout(() => {
					this.is_permit_speak = true;
				}, 12000);
				try {
					//权限
					await getSetting({
						scope: 'scope.record',
						url: '/pagesA/ar_navigation/index',
						content: '否重新开启录音权限，你的麦克风将用于录音功能',
						toast: '未授权麦克风权限,录音功能将无法使用',
					});
					console.log('按下说话');
					this.is_but_speak = true;
					this.clear_answer_person_fn(); //清除ai动画
					recorderManager.start({ format: 'wav', duration: 15000 }); //开始录音
				} catch (err) {
					this.is_permit_speak = true;
					console.log(err);
				}
			},
			//松开说话
			touchend_speak() {
				if (!this.is_but_speak) return;
				console.log('松开说话');
				recorderManager.stop();
				this.is_but_speak = false;
			},
			//停止监听事件
			onStop() {
				let _this = this;
				recorderManager.onStop(async function (res) {
					console.log('recorder stop' + JSON.stringify(res));
					if (res.duration < 1500) {
						uni.$u.toast('说话时间太短，请重新说话');
						_this.reset_status();
						return;
					}
					// innerAudioContext.src = res.tempFilePath;//自己声音
					_this.$store.commit('map/set_ai_loading', { question_loading: true });
					try {
						let result = await uploadFile({
							url: baseURLAi + '/api/voice/speech2text',
							filePath: res.tempFilePath,
							formData: { spot_id: _this.scenic_detail.spot_id },
							file: res,
						});

						console.log(result, '上传成功');
						if (!result.data) {
							_this.reset_status();
							uni.$u.toast('没有识别到语音内容');
							return;
						}

						_this.$store.commit('map/set_ai_loading', { question_loading: false });
						_this.$emit('touchend_speak',{ type: 'question', data: result.data.text,mode:1 });

						_this.$store.commit('map/set_ai_loading', { answer_loading: true });
						var service_post = { input_text: result.data.text, spot_id: _this.scenic_detail.spot_id};
						//文本类型映射规则type->mode【特：10000->0:位置指令】
						if(result.data.type == 10000)
						{
							service_post.mode = 0;
						}
						else
						{
							service_post.mode = 1;
						}
						let result_service = await service(service_post);
						_this.$store.commit('map/set_ai_loading', { answer_loading: false });
						
						console.log("api_respone==",result_service)
						const response = result_service.data?.response;
						const postData = { type: 'answer', data: result_service.data.text, ads:result_service.data.ads};
						if (response) {
							postData.data = response;
							postData.audio = result_service.data?.audio;
						}
						_this.$emit('touchend_speak', postData);
						_this.is_permit_speak = true;
						_this.answer_person_fn(); //AI 回答动画
					} catch (err) {
						_this.reset_status();
						console.log('语音失败', err);
					}

					// 监听播放事件
					innerAudioContext.onPlay(() => {
						console.log('开始播放录音');
					});

					// 监听播放结束事件
					innerAudioContext.onEnded(() => {
						console.log('录音播放结束');
					});
				});
			},
			reset_status() {
				this.is_permit_speak = true;
				this.$store.commit('map/set_ai_loading', { question_loading: false });
			},
			onError_fn() {
				let _this = this;
				recorderManager.onError((err) => {
					console.log('录音错误', err);
					_this.is_permit_speak = true;
				});
			},

			answer_person_fn() {
				// this.$store.commit('map/set_answer_person', true);
				// this.ai_time = setTimeout(() => {
				// 	this.$store.commit('map/set_answer_person', false);
				// }, 6000)
			},
			clear_answer_person_fn() {
				clearTimeout(this.ai_time);
				this.$store.commit('map/set_answer_person', false);
			},
			but2_map() {
				let str = this.map_nav_type_computed == 'ar_nav' ? 'map_nav' : 'ar_nav';
				this.$store.commit('map/set_map_nav_type', str);
			},
			goTo()
			{
				//推荐路线
				var _this =this;
				uni.navigateTo({
					url:'/pagesA/scenic_punch/line?spot_id='+ _this.scenic_detail.spot_id,
				})
			},
		},
		beforeDestroy() {
			innerAudioContext.stop();
		},
	};
</script>

<style lang="scss">
	.but1 {
		border-radius: 48rpx 48rpx 48rpx 48rpx;
		font-weight: 700;
		margin: 0;
		color: #3d3d3d;
		background-color: #fff;
		
	}

	.flex1 {
		flex: 1;
	}

	.but2 {
		background: linear-gradient(90deg, #0fbcd6 0%, #0cca91 100%);
		color: #fff;
	}

	.opacity_90 {
		opacity: 0.7;
	}
	/*取消button边框*/
	button::after{ border: none;} 
	.itemBox{ width: auto; display: flex;}
	.itemBoxLeft{width: 60rpx;}
	.itemBoxLeft image{width: 40rpx; height: 40rpx; margin:5rpx 10rpx;}
	.itemBoxRight{width: auto; text-align: center; line-height: 40rpx;}
	.itemBoxRight text{ font-size: 24rpx; font-weight: bold;}
</style>
